package MongoSrv

import (
	"context"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

//var mongoClient *mongo.Client
//var mongoDB *mongo.Database

type MongoDB struct {
	Client *mongo.Client
	DB *mongo.Database
}
var mongoDB *MongoDB

func Mongo() *MongoDB {
	if mongoDB == nil {
		panic("mongo client is null")
	}

	return mongoDB
}

/*func MongoDB() *mongo.Database {
	if mongoDB == nil {
		panic("mongodb is null")
	}

	return mongoDB
}*/

func MongoInit(config interface{}) *mongo.Client {
	mysqlConfig := config.(map[string]interface{})
	host := mysqlConfig["host"]
	port := mysqlConfig["port"]
	database := mysqlConfig["database"].(string)
	applyUri := fmt.Sprintf("mongodb://%s:%s", host, port)

	optionsClient := options.Client().ApplyURI(applyUri)
	client, err := mongo.Connect(context.Background(), optionsClient)
	if err != nil {
		panic(err.Error())
	}

	err = client.Ping(context.Background(), nil)
	if err != nil {
		panic(err.Error())
	}

	//mongoClient = client
	mongoDatabase := client.Database(database)
	mongoDB = &MongoDB{Client: client, DB: mongoDatabase}

	return client
}